<?php


namespace App\Models;


use App\Http\Controllers\WebApi\Business\ConfigBusiness;

class ImFtfGroup extends BaseModel
{
    protected $table = 'im_ftf_group';//面对面建群
    protected $range = 50;//距离，米
    protected $expire = 10;//过期时间，分钟

    //临时群组成员
    public function groupUsers()
    {
        return $this->hasMany(ImFtfGroupUsers::class, 'ftf_id', 'id');
    }

    //创建面对面群
    public function createGroup($param)
    {
        //找附近的临时群
        $res = $this->nearbyGroup([
            'password' => $param['password'],
            'longitude' => $param['longitude'],
            'latitude' => $param['latitude']
        ]);
        $ftf_id = $res['data'] ? $res['data']->id : null;
        //找不到自己创建
        if (!$ftf_id) {
            $this->user_id = $param['user_id'];
            $this->longitude = $param['longitude'];
            $this->latitude = $param['latitude'];
            $this->password = $param['password'];
            $this->timeout = ($this->expire * 60) + time();
            $this->status = 1;
            $this->save();
            $ftf_id = $this->id;
        }
        //将自己加入临时群
        $groupUsers = ImFtfGroupUsers::where('user_id', $param['user_id'])
            ->where('ftf_id', $ftf_id)->first();
        if (!$groupUsers) {
            $groupUsers = new ImFtfGroupUsers();
            $groupUsers->ftf_id = $ftf_id;
            $groupUsers->user_id = $param['user_id'];
            $groupUsers->save();
        }
        //查出最新数据
        $res = $this->nearbyGroup([
            'password' => $param['password'],
            'longitude' => $param['longitude'],
            'latitude' => $param['latitude']
        ]);
        if ($res['code'] === 0) {
            $data = $res['data'];
        }
        return ['code' => 0, 'msg' => 'ok', 'data' => $data];
    }

    //设置群状态，默认开启，1开启 2等待中 3关闭
    public function setStatus($param)
    {
        $group = new self();
        $group = $group->where('id', $param['id']);
        if (!isset($param['force'])) {
            $group = $group->where('user_id', $param['user_id']);
        }
        $data = $group->first();
        if ($data) {
            $data->status = $param['status'];
            $data->save();
        }
        return ['code' => 0, 'msg' => 'ok'];
    }

    //范围内的群
    public function nearbyGroup($param)
    {
        $group = new self();
        $group = $group->with(['groupUsers.user'])->select(['id', 'user_id', 'password', 'status', 'timeout', 'longitude', 'latitude'])
            ->selectRaw("ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN((" . $param['latitude']
                . " * PI() / 180 - latitude * PI() / 180) / 2),2) + COS(" . $param['latitude']
                . " * PI() / 180) * COS(latitude * PI() / 180) * POW(SIN((" . $param['longitude']
                . " * PI() / 180 - longitude * PI() / 180) / 2),2))) * 1000) AS distance");
        $group->whereBetween('status', [1, 2]);
        $group->where('password', $param['password']);
        $group->having('distance', '<=', $this->range);
        $data = $group->orderBy('distance', 'asc')->first();
        return ['code' => 0, 'msg' => 'ok', 'data' => $data];
    }

    //由临时群进入正式群
    public function intoGroup($param)
    {
        $data = self::find($param['ftf_id']);
        //如果临时群只有一个用户，则该用户创建群进入，否则单纯进群
        if (!$data) {
            return ['code' => 400, 'msg' => '群不存在'];
        }
        //临时群未生成真实群
        if (!$data->group_id) {
            //获取服务端分组配置
            $groupConfigs = ConfigBusiness::getServerGroupConfigs();
            //创建真实的群
            $imGroup = new ImGroup();
            $res = $imGroup->addGroup([
                'name' => '面对面群聊',
                'desc' => '欢迎入群',
                'open' => $groupConfigs['open'],
                'max_count' => $groupConfigs['max_count'],
                'users_count' => 1,
                'is_audit' => $groupConfigs['is_audit'],
                'is_allow' => $groupConfigs['is_allow'],
                'member' => null
            ], $param['user_id']);
            if ($res['code'] !== 0) {
                return ['code' => 400, 'msg' => '创建失败'];
            }
            $data->group_id = $res['group_id'];
            $data->save();
        } else {
            //添加单个群成员
            $imGroupUser = new ImGroupUser();
            $groupInfo = ImGroup::where('im_gid', $data->group_id)->select(['im_gid', 'user_id'])->first();
            $res = $imGroupUser->addSingleMember([
                'im_gid' => $groupInfo['im_gid'],
                'member_id' => $param['user_id']
            ], $groupInfo['user_id']);
            if ($res['code'] !== 0) {
                return ['code' => 400, 'msg' => $res['msg']];
            }
        }
        return ['code' => 0, 'msg' => 'ok', 'data' => $data->group_id];
    }

    //成员退出临时群，在等待界面进入群之前点击返回键退出
    public function memberExit($param)
    {
        //当前临时群信息
        $group = self::find($param['ftf_id']);
        if (!$group) {
            return ['code' => 400, 'msg' => '群不存在'];
        }
        //当前页面最后一个人退出关闭群
        $groupUserCount = ImFtfGroupUsers::where('ftf_id', $param['ftf_id'])->count();
        if ($groupUserCount <= 1) {
            if ($group->status !== 3) {
                $group->status = 3;
                $group->save();
            }
        }
        ImFtfGroupUsers::where('user_id', $param['user_id'])
            ->where('ftf_id', $param['ftf_id'])->delete();
        return ['code' => 0, 'msg' => 'ok'];
    }
}
